//
//  TZWUserAccoutViewModel.swift
//  Sinaweibotzw
//
//  Created by 檀志文 on 16/4/12.
//  Copyright © 2016年 ios檀志文. All rights reserved.
//

import UIKit

/// 专门处理 TZWUserAccount 模型相关操作，网络请求，字典转模型，归档，解档
class TZWUserAccoutViewModel: NSObject {
//    单例
    static let sharedInstance: TZWUserAccoutViewModel = TZWUserAccoutViewModel()
    
    private override init() {
        super.init()
 /// 单例的init方法调用一次
        userAccount = loadUserAccount()
    }
    // 账号模型。只要到单例就可以访问到全局通用
    var userAccount: TZWUserAccount?
    
    // 用户是否登录
    var useLogin: Bool{
        get{
            return userAccount != nil
        }
    }
    
    func loadAccessToken(code: String, loadAccessTokenCallBack: (error:NSError?) ->()){
        
        
        let urlString = accessTokenURLString
        
        let parameters = [
        "client_id": client_id,
        "client_secret": client_secret,
        "grant_type": grant_type,
        "code": code,
        "redirect_uri":redirect_uri
        ]
        /**
        *  发送请求 。post
        */
        TZWNetWorkTool.NetInstance.POST(urlString, parameters: parameters, progress: nil, success: { (task,responseObject) -> Void in
            let result = responseObject as? [String: AnyObject]
            
            if let dict = result {
               
//            这里之前出错一次 let userAccount ->self.userAccount
                
                self.userAccount = TZWUserAccount(dict: dict)
            
                
                self.saveUserAccount()
                
                loadAccessTokenCallBack(error: nil)
                
                }
            
            }) { (task, error) -> Void in
                loadAccessTokenCallBack(error: error)
        }
    }
    
    // 保存账号的模型
    private func saveUserAccount(){
        if let userAccount = self.userAccount {
            // 归档
            NSKeyedArchiver.archiveRootObject(userAccount, toFile: accountPath)
        }
    }
    
    // 从沙盒中解档UserAccount 对象
    
    func loadUserAccount() -> TZWUserAccount? {
        
        
        let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? TZWUserAccount
        
        HMPrint("tanzhiwen" + accountPath)
        
        if let account = userAccount where account.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            HMPrint("没有过期: \(account)")
            return account
        }
            return nil
    }
    
    
//    MARK: 获得用户的信息
    func loadUseInfo(loadUserInfoCallBack: (error: NSError?) ->()){
//        守卫
        guard let access_Token = userAccount?.access_token else {
//            能进来表示,userAccount?没有值,或者access_token没有值
//            HMPrint("userAccount ? 没有值，或者access_token 没有值")
//            return
//        }
//        
//        guard let uid = userAccount?.uid else {
//            // 能进来表示,userAccount?没有值,或者uid没有值
//
//            HMPrint("userAccount? 没有值，或者uid 没有值")
//            return
           let error = TZWNetWorkToolEnum.AccessTokenEmpty.error()
            loadUserInfoCallBack(error: error)
            return
        }
        guard let uid = userAccount?.uid else{
            // 能进来表示,userAccount?没有值,或者uid没有值
            HMPrint("userAccount?没有值,或者uid没有值")
            let error = TZWNetWorkToolEnum.UidEmpty.error()
            loadUserInfoCallBack(error: error)
            return
        }
        
//        //url
        let urlString = "https://api.weibo.com/2/users/show.json"
//       参数
        let parameters = [
            "access_token" : access_Token,
            "uid" : uid
        ]
//       发送请求
        TZWNetWorkTool.NetInstance.GET(urlString, parameters: parameters, progress: nil, success: { (task, responseObject) -> Void in
             HMPrint("加载用户信息成功:\(responseObject)")
            if let dict = responseObject as? [String: AnyObject]{
                self.userAccount?.screen_name = dict["screen_name"] as? String
                self.userAccount?.avatar_large = dict["avatar_large"]as? String
            
                // 将当前对象保存到沙盒中
                self.saveUserAccount()
                
                loadUserInfoCallBack(error: nil)
            }
            
            }) { (task, error) -> Void in
                loadUserInfoCallBack(error: error)
        }
        
//        
    }
}
